package cj.web.portal.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.web.admin.constants.Constants;
import cj.web.portal.service.CategoryVoService;
import cj.web.portal.service.MemberVoService;
import cj.web.portal.service.PointConfigVoService;
import cj.web.portal.service.VideoVoService;
import cj.web.yc.constants.MemberTypeEnum;
import cj.web.yc.constants.PayHistoryStatusEnum;

/**
 * 视频查看
 * @author Administrator
 *
 */
@Path("/videoVo")
public class VideoVoController extends BaseVoController{
	
	private static Logger logger = Logger.getLogger(VideoVoController.class.getName());
	
	@Autowired
    private CategoryVoService categoryService;
	@Autowired
    private VideoVoService videoService;
	@Autowired
    private PointConfigVoService pointConfigService;
	@Autowired
    private MemberVoService memberVoService;
	
	/**
	 * 视频页
	 * @param model
	 * @param categoryId
	 * @return http://localhost/yc-video/video/videoPage?categoryId=1
	 * @throws Exception
	 */
	@Get("videoPage")
	public String videoPage(Model model,@Param("categoryId") String categoryId,
			HttpServletRequest request) throws Exception {
		
		List<Map> pCategory = categoryService.queryById(Integer.parseInt(categoryId));
		if(pCategory!=null && pCategory.size()>0){
			model.add("category", pCategory.get(0));
			List<Map> subCategory = categoryService.queryByPid(Integer.parseInt(categoryId));
			
			String params = returnRequestParams(request,subCategory,categoryId);
			model.add("params", params);
			
			//类目列表与子列表
			for(Map rep:subCategory){
				int pid=Integer.parseInt(rep.get("id").toString());
				List<Map> subCategorylis = categoryService.queryByPid(pid);
				rep.put("subCategorylis", subCategorylis);
			}
			
			String[] paramslis = params.split("@,@");
			for(int i=0;i<paramslis.length;i++){
				String strParams = paramslis[i];
				List<Map> categorylis = categoryService.queryCategorylis(strParams, categoryId);
				if(categorylis!=null && categorylis.size()>0){
					int pid = Integer.parseInt(categorylis.get(0).get("pid").toString());
					List<Map> p_Categorylis = categoryService.queryById(pid);
					String pp_value = p_Categorylis.get(0).get("value").toString();
					
					for(Map rep:subCategory){
						if(pp_value.equals(rep.get("value").toString())){
							rep.put("subCategorylis", categorylis);
						}
					}
				}
			}
			
			model.add("subCategory", subCategory);
		}
		
		return "/views/portal/video_list.vm";
	}
	
	/**
	 * 返回request的参数的值
	 * @param request
	 * @return
	 */
	private String returnRequestParams(HttpServletRequest request,List<Map> subCategory,String categoryId){
		String strlis = categoryId;
		Map map=request.getParameterMap();
		Set keSet=map.entrySet();
		
		for(Map rep:subCategory){
			
			for(Iterator itr=keSet.iterator();itr.hasNext();){
				Map.Entry me=(Map.Entry)itr.next();
				Object ok=me.getKey();
				Object ov=me.getValue();
				String[] value=new String[1];
				if(ov instanceof String[]){
					value=(String[])ov;
				}else{
					value[0]=ov.toString();
				}
				if(ok.toString().equals(rep.get("value").toString())){
					strlis+="@,@"+value[0].toString();
				}
			}
			
		}
		
		return strlis;
	}
	
	/**
	 * 类目lis
	 * @param categoryId
	 * @return http://localhost/yc-video/video/categoryId?categoryId=23
	 * @throws Exception
	 */
	@Get("getCategorylis")
	public String getCategorylis(@Param("categoryId") int categoryId) throws Exception {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		//类目lis
		List<Map> categorylis = categoryService.queryByPid(categoryId);
		String categoryIds ="";
		for(Map rep :categorylis){
			categoryIds+=rep.get("id").toString()+",";
		}
		jo.put("categorylis", categorylis);
		jo.put("all", categoryIds.substring(0, categoryIds.length()-1));
		return "@"+jo.toString();
	}
	
	/**
	 * 类目lis——视频列表
	 * @param categoryIds
	 * @param start
	 * @param length
	 * @return http://localhost/yc-video/video/getVideolis?categoryIds=23,25&start=0&length=3
	 * @throws Exception
	 */
	@Get("getVideolis")
	public String getVideolis(@Param("categoryIds") String categoryIds,
			@Param("start") int start,@Param("length") int length) throws Exception {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		Map rep = videoService.query(categoryIds.replace("@", "%"), start*length, length);
		jo.put("list", rep.get("videolis"));
		jo.put("totalCount", rep.get("size"));
		return "@"+jo.toString();
	}
	
	/**
	 * 视频详情
	 * @param videoId
	 * @return http://localhost/yc-video/video/getVideoDetail?videoId=1
	 * @throws Exception
	 */
	@Get("getVideoDetail")
	public String getVideoDetail(HttpServletRequest request,Model model,@Param("videoId") int videoId,
			@Param("categoryId") int categoryId,Invocation inv) throws Exception {
		String memberId = getCookieValueByName(request, "memberId");
		Map rep = videoService.queryVideoDetail(videoId,memberId,inv);
		List<Map> pCategory = categoryService.queryById(categoryId);
		
		//开始
		boolean flagStart = true;
		//结束
		boolean flagEnd = true;
		
		Map repMember = (Map) rep.get("member");
		if(repMember!=null){
			model.add("member", rep.get("member"));
			String memberType = repMember.get("type").toString();
			if(MemberTypeEnum.LS.getValue()==Integer.parseInt(memberType)){
				//账号类型是老师
				flagStart = false;
				flagEnd = false;
			}else{
				//账号类型是学生
				List<Map> replis = videoService.videoWatchHistory(Integer.parseInt(memberId), videoId);
				if(replis!=null && replis.size()>0){
					flagStart = false;
					int status = Integer.parseInt(replis.get(0).get("status").toString());
					if(PayHistoryStatusEnum.END.getValue()==status){
						flagEnd = false;
					}
				}
			}
		}
		
		if(pCategory!=null && pCategory.size()>0){
			model.add("category", pCategory.get(0));
		}
		
		model.add("videoDetail", rep.get("videoDetail"));
		model.add("videoDetailOtherlis", rep.get("videoDetailOtherlis"));
		
		//取加载的值
		ServletContext context = inv.getServletContext();  
        HashMap dictionaryInfoMap = (HashMap)context.getAttribute("dictionaryInfoMap");
		Map pointConfigPointNumRep = (Map) dictionaryInfoMap.get("pointConfigPointNum");//配置积分
		Integer video_end_code_pointnum = (Integer) pointConfigPointNumRep.get(VIDEO_END_CODE);
		Integer video_begin_code_pointnum = (Integer) pointConfigPointNumRep.get(VIDEO_BEGIN_CODE);
		model.add("video_end_code_pointnum", video_end_code_pointnum);
		model.add("video_begin_code_pointnum", video_begin_code_pointnum);
		model.add("flagStart", flagStart);
		model.add("flagEnd", flagEnd);
		return "/views/portal/video_detail.vm";
	}
	
	public final static String IS_LOGIN_CODE = "IS_LOGIN";//是否登录
	public final static String VIDEO_BEGIN_CODE = "VIDEO_BEGIN";//视频开始积分
	public final static String VIDEO_END_CODE = "VIDEO_END";//视频结束积分
	
	@Get("videoStart")
	public String videoStart(@Param("videoId") int videoId,@Param("categoryId") int categoryId,
			Invocation inv,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		//取加载的值
		ServletContext context = inv.getServletContext();  
        HashMap dictionaryInfoMap = (HashMap)context.getAttribute("dictionaryInfoMap");
        
		Map pointConfigRep = (Map) dictionaryInfoMap.get("pointConfigRep");//配置
		Map pointConfigPointNumRep = (Map) dictionaryInfoMap.get("pointConfigPointNum");//配置积分
		
		//配置积分控制列表
		List<Map> is_login_lis = (List<Map>) pointConfigRep.get(IS_LOGIN_CODE);
		List<Map> video_begin_lis = (List<Map>) pointConfigRep.get(VIDEO_BEGIN_CODE);
		
		//积分分值列表
		Integer video_begin_code_pointnum = (Integer) pointConfigPointNumRep.get(VIDEO_BEGIN_CODE);
		
		List<Map> videolis = videoService.getVideoDetail(videoId);
		if(videolis!=null && videolis.size()>0){
			//视频类目ID
			if(is_login_lis!=null && is_login_lis.size()>0){
				//视频类目
				String categoryIds = videolis.get(0).get("categoryIds").toString();
				boolean flag = false;//是否存在
				//类目列表
				for(int i=0;i<categoryIds.split(",").length;i++){
					flag = returnContainsFlag(is_login_lis, categoryIds.split(",")[i].toString());
					if(flag) break;
				}
				
				if(flag){
					//判断登录
					if(isLogin(request)){
						//已登录
						//类目列表
						for(int i=0;i<categoryIds.split(",").length;i++){
							flag = returnContainsFlag(video_begin_lis, categoryIds.split(",")[i].toString());
							if(flag) break;
						}
						if(flag){
							//需要扣豆
							String memberId = getCookieValueByName(request, "memberId");
							Map rep = videoService.videoStart(videoId, Integer.parseInt(memberId),video_begin_code_pointnum,categoryId);
							jo.put("returnFlag", rep.get("returnFlag"));
							jo.put("returnCode", rep.get("returnCode"));
						}else{
							//不需要扣豆
							jo.put("returnFlag", Constants.returnObj.returnFlag_true);
							jo.put("returnCode", Constants.returnObj.returnCode.code_0);
						}
						
						return "@"+jo.toString();
					}else{
						//未登录
						jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
						jo.put("returnCode", Constants.returnObj.returnCode.code_3);
						return "@"+jo.toString();
					}
				}else{
					//判断不需要登录
					jo.put("returnFlag", Constants.returnObj.returnFlag_true);
					jo.put("returnCode", Constants.returnObj.returnCode.code_0);
					return "@"+jo.toString();
				}
			}
		}
		
		return "@"+jo.toString();
	}
	
	/**
	 * 
	 * @param plis
	 * @param sublis
	 * @return
	 */
	public boolean returnContainsFlag(List<Map> plis,String value) {
		List<String> sublis = new ArrayList<String>();
		sublis.add(value);
		List<String> l_plis = new ArrayList<String>();
		for(Map rep:plis){
			l_plis.add(rep.get("categoryId").toString());
		}
		
		boolean contains = l_plis.containsAll(sublis);
		return contains;
	}
	
	@Get("videoEnd")
	public String videoEnd(@Param("videoId") int videoId,@Param("categoryId") int categoryId,
			Invocation inv,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		//取加载的值
		ServletContext context = inv.getServletContext();  
        HashMap dictionaryInfoMap = (HashMap)context.getAttribute("dictionaryInfoMap");
        
		Map pointConfigRep = (Map) dictionaryInfoMap.get("pointConfigRep");//配置
		Map pointConfigPointNumRep = (Map) dictionaryInfoMap.get("pointConfigPointNum");//配置积分
		
		//配置积分控制列表
		List<Map> video_end_lis = (List<Map>) pointConfigRep.get(VIDEO_END_CODE);
		//积分分值列表
		Integer video_end_code_pointnum = (Integer) pointConfigPointNumRep.get(VIDEO_END_CODE);
		List<Map> videolis = videoService.getVideoDetail(videoId);
		
		if(videolis!=null && videolis.size()>0){
			
			String categoryIds = videolis.get(0).get("categoryIds").toString();
			boolean flag = false;//是否存在
			//类目列表
			for(int i=0;i<categoryIds.split(",").length;i++){
				flag = returnContainsFlag(video_end_lis, categoryIds.split(",")[i].toString());
				if(flag) break;
			}
			
			if(flag){
				//存在，需要加分
				String memberId = getCookieValueByName(request, "memberId");
				if(memberId!=null && !"".equals(memberId)){
					Map rep = videoService.videoEnd(videoId, Integer.parseInt(memberId), video_end_code_pointnum);
					jo.put("returnFlag", rep.get("returnFlag"));
					jo.put("returnCode", rep.get("returnCode"));
				}else{
					//未登录
					jo.put("returnFlag", Constants.returnObj.returnFlag_true);
					jo.put("returnCode", Constants.returnObj.returnCode.code_0);
				}
			}else{
				//不存在
				jo.put("returnFlag", Constants.returnObj.returnFlag_true);
				jo.put("returnCode", Constants.returnObj.returnCode.code_0);
			}
			
			return "@"+jo.toString();
		}
		
		return "@"+jo.toString();
	}
}